/**
 * 
 */
package com.hw.hcit.feature;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;

import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.service.persistentdata.PersistentDataBlockManager;
import com.hw.hcit.sensor.EmSensor;
/**
 * @author gaoshengpan
 *
 */
public class ApproachTestItem extends JTestItem implements OnClickListener {
    private ImageView[] images = new ImageView [2];
    private SensorEventListener mProximityListener;
    private SensorManager mSensorManager ;
    Sensor mProimitySensor;
    private boolean powerClicked = false;
    private String TAG = "ApproachTestItem";
    private Button mButton1,mButton2,mButton3,mButton4;
    private TextView textView,textView1;
    private boolean calibrate = false;
    private static BufferedReader br;
    private static File file ;
    private static FileInputStream fileInputStream ;
    private static InputStreamReader inpuStreamReader ;
    private static boolean access,away;
    private static int mMin = 0;
    private static int mMax = 0;
    private static int ret = 0;
    
    private final int CALCULATE_MIN_SUCCESS = 0;
    private final int CALCULATE_MIN_FAIL = 1;
    private final int CALCULATE_MAX_SUCCESS = 2;
    private final int CALCULATE_MAX_FAIL = 3;
    private final int CALIBRATE_SUCCESS = 4;
    private final int CALIBRATE_FAIL = 5;
    
    private String minString,maxString,calculateSuc,calculateFai,calibrationSuc,calibrationFai;
    Toast pToast;
    Context mContext;
    /**
     * @param cb
     */
    public ApproachTestItem(JCtrlCallback cb) {
        super(cb);
        // TODO Auto-generated constructor stub
    }

    /**
     * 
     */
    public ApproachTestItem() {
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = Config.GetActivity().getApplicationContext();
        if(mContext == null){
            Log.d(TAG, "---------->0");
        }
        mSensorManager = (SensorManager)Config.GetActivity().getApplicationContext().getSystemService("sensor");
        
        mProximityListener = new SenListener();
        
        if(mSensorManager == null){
            Log.d(TAG, "---------->00");
        }
        if(mProximityListener == null){
            Log.d(TAG, "---------->11");
        }
        if(mProimitySensor == null){
            Log.d(TAG, "---------->2");
        }
    }

    Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
           super.handleMessage(msg);

               // TODO Auto-generated method stub
           	int ret2 = EmSensor.doPsensorCalibration(mMin, mMax);
            	if(ret2 ==1){
            	    calibrate = true;
            	   showPToast(calibrationSuc);
                   Log.d(TAG, "doPsensorCalibration----->"+"success");
            	}else{
            		showPToast(calibrationFai);
            		Log.d(TAG, "doPsensorCalibration--res--->"+ret2);
            	}

        }
     };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View rootView = inflater.inflate(R.layout.approach_test, container,
                false);
        images[0] = (ImageView) rootView.findViewById(R.id.imageView1);
        images[1] = (ImageView) rootView.findViewById(R.id.imageView2);
        mButton1 = (Button) rootView.findViewById(R.id.button1);
        mButton2 = (Button) rootView.findViewById(R.id.button2);
        mButton3 = (Button) rootView.findViewById(R.id.button3);
        mButton4 = (Button) rootView.findViewById(R.id.button4);
        textView = (TextView) rootView.findViewById(R.id.textView1);
        textView1 = (TextView) rootView.findViewById(R.id.textView2);
        minString = getString(R.string.calibrate_min_value);
        maxString = getString(R.string.calibrate_max_value);
        calculateSuc = getString(R.string.calculate_success);
        calculateFai = getString(R.string.calculate_fail);
        calibrationSuc = getString(R.string.calibrate_success);
        calculateFai = getString(R.string.calibrate_fail);
        mProimitySensor = mSensorManager.getDefaultSensor(8);
        boolean flag = mSensorManager.registerListener(mProximityListener, mProimitySensor, 3);
        String s = (new StringBuilder()).append("bSucceed is ").append(flag)
                .toString();
        if(mProximityListener != null && mProimitySensor!=null ){
        Log.d(TAG, s);
        }

        mButton1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(Config.CURR_PROJECT.isAuto()){
                    if (!Config.ageingTested) {
                        rewriteOneByteOfNv2499(11, 'P');
                    } else {
                        rewriteOneByteOfNv2499(42, 'P');
                    }
                }
                testFinish(true, 1, true);
            }
        });
        mButton2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(Config.CURR_PROJECT.isAuto()){
                    if (!Config.ageingTested) {
                        rewriteOneByteOfNv2499(11, 'F');
                    } else {
                        rewriteOneByteOfNv2499(42, 'F');
                    }
                }
                testFinish(true, 1, false);
            }
        });
        
       mButton3.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                ret = EmSensor.calculatePsensorMinValue();
            	if(ret == 1){
            		mMin = EmSensor.getPsensorMinValue();
            		textView.setText(minString+mMin);
            		showPToast(calculateSuc);
            		Log.d(TAG, "PsensorMinValue----mMin------>"+mMin);
            	}else{
            		showPToast(calculateFai);
            		Log.d(TAG, "calculatePsensorMinValue()------>"+"fail");
            	}
            }
        });
        mButton4.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
            	int ret1 =EmSensor.calculatePsensorMaxValue();
                if(ret1 ==1){
                	mHandler.sendEmptyMessageDelayed(0, 1000);
            		mMax = EmSensor.getPsensorMaxValue();
            		textView1.setText(maxString+mMax);
            		showPToast(calculateSuc);
                    Log.d(TAG, "PsensorMinValue-----mMax----->"+mMax);
            	}else{
            		showPToast(calculateFai);
            		Log.d(TAG, "calculatePsensorMaxValue()------>"+"fail");
            	}
                
            }
        });
        return rootView;
    }

    @Override
    public void onDetach() {
    	// TODO Auto-generated method stub
    	super.onDetach();
    	mHandler.removeMessages(0);
    }
    
    @Override
    public void onPause() {
    	// TODO Auto-generated method stub
    	super.onPause();
    	mHandler.removeMessages(0);
    }

    /* (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        
    }

    private class SenListener implements SensorEventListener

    {

        public void onAccuracyChanged(Sensor sensor, int i) {
        }

        public void onSensorChanged(SensorEvent sensorevent) {
        
            StringBuilder stringbuilder;
            Log.d(TAG, "onSensorChanged-->"+"sensorevent.values[0="+sensorevent.values[0]);
            String s1;
            if (sensorevent.values[0] == 0) {
                /*15-09-07 gaoshenpan fix approach calibrate begin*/
                if(calibrate){
                    images[0].setVisibility(4);
                    images[1].setVisibility(0);
                    access =true;
                }
            } 
             if(sensorevent.values[0] == 1 && access){
                images[0].setVisibility(0);
                images[1].setVisibility(4);
                away  =true;
                mButton1.setEnabled(true);
                
            }
        }
    }

    public static String readFile(String filePath){   
        String res="";   
        /*15-12-01 gaoshenpan fix it be more efficient begin */
        
        try{   
            file = new File(filePath);
            fileInputStream  =new FileInputStream(file);
            inpuStreamReader = new InputStreamReader(fileInputStream);
             br = new BufferedReader(inpuStreamReader);
             /*15-12-01 gaoshenpan fix it be more efficient end */
            String str=null;
            while((str=br.readLine())!=null){
                res+=str;
            }  
        }   
        catch(Exception e){   
         e.printStackTrace();   
        } 
        finally {
            Log.d("hh", "finally----------->closeIO");
            try {
                if (br != null) {
                    br.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }

        }
        return res;   
    }  
    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        access = false;
        away = false;
        powerClicked = false;
        mButton1.setEnabled(false);
        calibrate = false;
        images[0].setVisibility(0);
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        SensorManager sensormanager = mSensorManager;
        SensorEventListener sensoreventlistener = mProximityListener;
        sensormanager.unregisterListener(sensoreventlistener);
    }
    public void showPToast(String s) {
        pToast.makeText(mContext, s,
				Toast.LENGTH_SHORT).show();
    }

}
